// pages/cartList/cartList.js
let showData = require('../../utils/data')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsCartList: [],
    allTotal: 0
  },

  //处理加减操作
  oper: function (e) {
    console.log(e);
    var isDelete = false;
    var index = e.currentTarget.dataset.index
    var count = this.data.goodsCartList[index].count
    console.log(count);
    var temp = "goodsCartList[" + index + "].count"
    if (e.currentTarget.dataset.type == '+') {
      this.setData({
        [temp]: ++count
      })
    } else {
      if (count > 1) {
        this.setData({
          [temp]: --count
        })
      }else{
        isDelete = true //用于标记该商品需要被删除
      }
    }
    var that = this
    var cartList = wx.getStorageSync("cartList")
    if(isDelete){
      wx.showModal({
        title:'提示',
        content:'你是否要将该商品移除购物车',
        success:res=>{
          if(res.confirm){
            //cartList.splice(index,1)
           var newCart = []
           for(let i=0;i<cartList.length;i++){
             if(i != index){
              newCart.push(cartList[i])
             }
           }
           wx.setStorageSync('cartList', newCart)
           that.getNewPage()
          }
        }
      })
    }else{
      cartList[index].count = count 
      wx.setStorageSync('cartList', cartList)
    
    }
   /* var allTotal = 0;
    var goodsCartList = this.data.goodsCartList;
    for(let i=0;i<goodsCartList.length;i++){
      allTotal= allTotal + goodsCartList[i].detail.goodsPrice * goodsCartList[i].count
    }
    this.setData({
      allTotal:allTotal
    })*/
   
   
  },


  getNewPage:function(){
    var cartIndexList = wx.getStorageSync('cartList')
    var cartList = showData.getGoodsListByIndex(cartIndexList)
    var goodsCartList = [];
    var allTotal = 0
    for (let i = 0; i < cartList.length; i++) {
      goodsCartList.push({
        detail: cartList[i],
        count: cartIndexList[i].count
      })
      allTotal = allTotal + cartList[i].goodsPrice * cartIndexList[i].count
    }
    this.setData({
      goodsCartList: goodsCartList,
      allTotal: allTotal
    })
  },

  onShow: function () {
    this.getNewPage()
  },
})